import { CanvasContext } from './designType';
import { Point } from './Point';
import {ToolManager, ToolType, SubCategory} from './ToolManager';
import { Window } from './Window';

Page(
  
  {
  data: {
    startPoint: null as Point | null,
    isDrawing: false,
    isTwoFinger: false,
    initialDistance: 0,
    selectedTool: "",
    scale: 1,
    ctx: null as CanvasContext | null, // 存储2D绘图上下文
    canvas: null as  WechatMiniprogram.Canvas | null, // 存储canvas节点
    canvasOffsetTop: 0 ,
    subCategories: [] as SubCategory[],
    toolManager: null as ToolManager | null, // Declare toolManager as nullable
    window: null as Window | null,
    interactiveShapes: [] as Array<{ type: string; id: string; rect: { x: number, y: number, width: number, height: number } }>,

  },

  onShow() {
    const customTabBar = this.getTabBar();
    if (customTabBar) {
      customTabBar.setData({ selected: 1 }); // 设置为画图页面的索引，假设为 0
    }
  },

  onLoad() {
    const toolManager = new ToolManager();
    this.data.window = new Window();

    // Set toolManager and subCategories in setData
    this.setData({
      toolManager: toolManager,
      subCategories: toolManager.getSubCategories('frame') // Use the local variable here
    });

   
    wx.createSelectorQuery().select('#windowCanvas').boundingClientRect(rect => {
      this.setData({ 
        canvasOffsetTop:rect.top,
      });
    }).exec();
    // 获取 canvas 节点和 2D 上下文
    wx.createSelectorQuery()
      .select('#windowCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node as WechatMiniprogram.Canvas;
        const ctx = canvas.getContext('2d') as CanvasContext;
      

        // 设置画布尺寸（需要根据实际大小调整）
        const dpr = wx.getWindowInfo().pixelRatio; // 获取设备像素比
        console.log(dpr);
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        ctx.scale(dpr, dpr); // 缩放上下文，适配高分屏
        this.setData({ 
          canvas, 
          ctx,
        });
      });
  },

  selectMainCategory(event: any) {
    const category = event.currentTarget.dataset.category;
    const subCategories = this.data.toolManager!.getSubCategories(category);
    this.setData({ subCategories });
  },

  // Method to handle selecting a tool
  selectTool(event:WechatMiniprogram.TouchEvent) {
    const tool = event.currentTarget.dataset.tool;
    console.log("Selected tool:", tool);
    this.data.toolManager?.setTool(tool);
    // Your tool selection logic here
  },

  addInteractiveShape(type: string, id: string, rect: { x: number, y: number, width: number, height: number }) {
    this.data.interactiveShapes.push({ type, id, rect });
  },

  onTouchStart(event: WechatMiniprogram.TouchEvent) {
    if (event.touches.length === 1) {
      const touch = event.touches[0];
      const startPoint = new Point(
        touch.clientX,
        touch.clientY-this.data.canvasOffsetTop)
      this.setData({
        startPoint: startPoint,
        isDrawing: true,
        isTwoFinger: false
      });
    } else if (event.touches.length === 2) {
      const [touch1, touch2] = event.touches;
      const initialDistance = this.getDistance(touch1, touch2);
      this.setData({
        isTwoFinger: true,
        initialDistance
      });
    }
  },

  onTouchMove(event: WechatMiniprogram.TouchEvent) {
    if (this.data.isTwoFinger && event.touches.length === 2) {
      const [touch1, touch2] = event.touches;
      const currentDistance = this.getDistance(touch1, touch2);
      
      const scale = this.data.scale + 0.00005 *(currentDistance - this.data.initialDistance);
      console.log(scale);
      this.setData({ scale });
      this.drawScaledWindow(scale);
    } else if (!this.data.isTwoFinger && event.touches.length === 1 && this.data.isDrawing) {
      const touch = event.touches[0];
      const currentX = touch.clientX;
      const currentY = touch.clientY-this.data.canvasOffsetTop;
      const currentPoint = new Point(currentX, currentY)
      if (this.data.startPoint) {
        this.drawMoving(this.data.startPoint, currentPoint);
      }


    }
  },

  onTouchEnd() {
    
    this.setData({ isDrawing: false, isTwoFinger: false });
    if (this.data.toolManager) {
      const toolpoints = this.data.toolManager?.getDrawStrategy()?.getPoints();
      if (toolpoints?.type == 'rect') {
        this.data.window?.addFrame(toolpoints);
      }
      else if (toolpoints?.type == 'line') {
        this.data.window?.addMullion(toolpoints, this.data.toolManager.getTool());
      }
    }
    this.clearCanvas()
    if (this.data.ctx) {
      this.data.window?.draw(this.data.ctx);
    }
    
    // this.drawComplete();
  },

  drawMoving(startPoint :Point, currentPoint:Point) {  
    const strategy = this.data.toolManager?.getDrawStrategy();
    const points = [startPoint, currentPoint];
    
    if (strategy && this.data.ctx && this.data.canvas) {
      this.data.ctx.clearRect(0,0,this.data.canvas.width, this.data.canvas.height);
      strategy.drawStroke(
        this.data.ctx,               // Canvas 上下文
        this.data.canvas,            // Canvas 实例
        points,                      // 点集合
        'green',                      // 线条颜色
        2,                           // 线条宽度
        true                         // 是否使用虚线
      );
    } else {
      wx.showToast({
        title: "绘制失败: 缺少绘制策略或 Canvas 实例。",
        icon: "none",               // 设置为无图标样式
        duration: 2000               // 显示时间（单位为毫秒）
      });
    }
    this.data.window?.draw(this.data.ctx!);


  },

  getDistance(touch1: WechatMiniprogram.TouchDetail, touch2: WechatMiniprogram.TouchDetail) {
    const dx = touch2.clientX - touch1.clientX;
    const dy = touch2.clientY - touch1.clientY;
    return Math.sqrt(dx * dx + dy * dy);
  },

  drawScaledWindow(scale: number) {
    const ctx = this.data.ctx;
    if (!ctx) return;

    ctx.scale(scale, scale);
    ctx.restore();
  },

  clearCanvas() {
    const ctx = this.data.ctx;
    if (!ctx) return;

    ctx.clearRect(0, 0, this.data.canvas!.width, this.data.canvas!.height);
    
  },

  clear() {
    const ctx = this.data.ctx;
    if (!ctx) return;

    ctx.clearRect(0, 0, this.data.canvas!.width, this.data.canvas!.height);
    this.data.window = new Window();
    
  },

  trans3D() {
    if (this.data.window) {
      wx.setStorageSync('windowData', this.data.window);
    }
    wx.navigateTo({
      url: '/pages/xr/index' // 跳转到 3D 页面
    });
  }


});
